package com.tanhua.manage.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.manage.mapper.AdminMapper;
import com.tanhua.manage.mapper.AdminRoleMapper;
import com.tanhua.manage.pojo.Admin;
import com.tanhua.manage.pojo.AdminRole;
import com.tanhua.manage.vo.AdminRoleVo;
import com.tanhua.manage.vo.Pager;
import com.tanhua.manage.vo.RoleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class PressionService {

    @Autowired
    private AdminRoleMapper adminRoleMapper;


    public Pager<RoleVo> findRoleByPage(Integer page, Integer pageSize, String roleName) {
        IPage<AdminRole> adminRoleIPage = new Page<>(page,pageSize);
        Wrapper<AdminRole>  queryWrapper = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(roleName)){
            int length = roleName.length();
            System.out.println(length);
            ((QueryWrapper<AdminRole>) queryWrapper).like("role_name",roleName);
        }
        //((QueryWrapper<AdminRole>) queryWrapper).orderByDesc("created");
        adminRoleMapper.selectPage(adminRoleIPage, queryWrapper);
        List<RoleVo> roleVos = new ArrayList<>();
        List<AdminRole> records = adminRoleIPage.getRecords();
        for (AdminRole record : records) {
            RoleVo roleVo = new RoleVo();
            roleVo.setId(record.getId());
            if(StrUtil.isNotEmpty(record.getRoleDescribe())){
                if(record.getRoleDescribe().length()>10){
                    record.setRoleDescribe(record.getRoleDescribe().substring(0,10)+"...");
                }
            }
            roleVo.setName(record.getRoleName());
            roleVo.setDesc(record.getRoleDescribe());
            Integer state = record.getState();
            if(state == 1){
                roleVo.setState("启用");
            }else {
                roleVo.setState("禁用");
            }
            roleVos.add(roleVo);
        }
        return new Pager<RoleVo>(
                adminRoleIPage.getTotal(),
                adminRoleIPage.getSize(),
                adminRoleIPage.getSize(),page,
                roleVos
        );
    }

    /**
     * 权限列表查询
     */
    @Autowired
    private AdminMapper adminMapper;
    public Pager<AdminRoleVo> findAdminPression(Integer page, Integer pageSize, String adminName) {
        // 分页模糊查询
        IPage<AdminRoleVo> adminRole = this.adminMapper.findAdminRole(new Page<>(page, pageSize), adminName == null ? null : adminName);
        return new Pager<>(adminRole.getTotal(),adminRole.getSize(),adminRole.getPages(),page,adminRole.getRecords());
    }

    /*
    2.2 操作：新建角色、修改、删除、停用（点击，改变列表中的状态）


    * */
    public String insertRole(AdminRole adminRole,String pressionIds) {
        /*
            2.3 新建角色
            2.3.1 角色名称（限制输入1-10个字），做唯一性验证
            2.3.2 角色描述（限制输入0-20个字）
            2.3.3开通权限，必选、不定项选择
        */
        String roleName = adminRole.getRoleName();
        Wrapper<AdminRole> queryWrapper = new QueryWrapper<>();
        ((QueryWrapper<AdminRole>) queryWrapper).eq("role_name",roleName);
        AdminRole selectRole = this.adminRoleMapper.selectOne(queryWrapper);
        if(selectRole != null){
            return "该角色已存在，请修改角色名后新增";
        }
        if( StrUtil.isEmpty(roleName) || roleName.length() > 10){
            return "角色名只能1-10个字";
        }
        String roleDescribe = adminRole.getRoleDescribe();
        if(StrUtil.isNotEmpty(roleDescribe)){
            if(roleDescribe.length() > 20){
                return "描述只能20字以内";
            }
        }
        this.adminRoleMapper.insert(adminRole);

        Wrapper<AdminRole> queryWrapper1 = new QueryWrapper<>();
        ((QueryWrapper<AdminRole>) queryWrapper1).eq("role_name",roleName);
        AdminRole role = this.adminRoleMapper.selectOne(queryWrapper1);
        String[] split = StrUtil.split(pressionIds, ",");
        // 默认首页权限
        this.adminRoleMapper.insertRoleIdAndPressionId(role.getId(),1);
        for (String s : split) {
            if(1 == Integer.valueOf(s)){ // 不重复添加
                continue;
            }
            this.adminRoleMapper.insertRoleIdAndPressionId(role.getId(),Integer.valueOf(s));
        }

        return "新增成功";
    }
    // 删除角色
    public String deleteRoleById(Integer id) {
        try {
            int i = this.adminRoleMapper.deleteById(id);
            if(i>0){
                return "删除成功";
            }
            return "所删除id不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "删除失败";
    }

    //修改角色
    public String updateRoleById(AdminRole adminRole) {

        try {
            String roleName = adminRole.getRoleName();
            Wrapper<AdminRole> queryWrapper = new QueryWrapper<>();
            ((QueryWrapper<AdminRole>) queryWrapper).eq("role_name",roleName);
            ((QueryWrapper<AdminRole>) queryWrapper).ne("id",adminRole.getId()); //这里有坑
            List<AdminRole> adminRoles = this.adminRoleMapper.selectList(queryWrapper);
            if(adminRoles.size() > 0){
                return "该角色已存在，请修改角色名后新增";
            }
            if( StrUtil.isEmpty(roleName) || roleName.length() > 10){
                return "角色名只能1-10个字";
            }
            String roleDescribe = adminRole.getRoleDescribe();
            if(StrUtil.isNotEmpty(roleDescribe)){
                if(roleDescribe.length() > 20){
                    return "描述只能20字以内";
                }
            }
            int i = this.adminRoleMapper.updateById(adminRole);
            if(i>0){
                return "修改成功";
            }
            return "所修改管理员id不存在";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "修改失败";
    }

    //修改状态
    public String updateRoleState(Integer id, Integer state) {
        AdminRole role = this.adminRoleMapper.selectById(id);
        if(role == null){
            return "修改的用户管理员不存在";
        }
        if(role.getState() == state){
            return "不能修改为相同状态";
        }
        role.setState(state);
        int i = this.adminRoleMapper.updateById(role);
        if(i>0){
            return "修改成功";
        }
        return "所修改管理员id不存在";
    }

    // 新增管理员用户

    public String insertAdmin(Admin admin, String roleIds) {
        try {
        /*2.3 新建账号
        2.3.1 名称（限制输入2-4个字），做唯一性验证
        2.3.2 手机号（限制输入1-11个字），做唯一性验证,验证格式
        2.3.3 密码，默认123456（不可修改)
        2.3.4 开通权限，必选、不定项选择*/
            // 用户名判断
            String username = admin.getUsername();
            Wrapper<Admin> queryWrapper = new QueryWrapper<>();
            ((QueryWrapper<Admin>) queryWrapper).eq("username",username);
            Admin user = this.adminMapper.selectOne(queryWrapper);
            if(user != null){
                return "用户名已存在";
            }
            if(StrUtil.isEmpty(username)){
                return "用户名不能为空";
            }
            if(username.length()>4 || username.length()<2){
                return "用户名长度限制在2-4个字";
            }
            // 手机号判断
            String phone = admin.getPhone();
            if(StrUtil.isEmpty(phone)){
                return "非超级管理员手机号不能为空";
            }
            Wrapper<Admin> queryWrapper1 = new QueryWrapper<>();
            ((QueryWrapper<Admin>) queryWrapper1).eq("phone",phone);
            Admin admin1 = this.adminMapper.selectOne(queryWrapper1);
            if(admin1 != null){
                return "手机号不能重复";
            }
            if(phone.length() != 11){
                return "手机号必须为中国11位手机号码";
            }
            // 设定固定密码123456
            admin.setPassword(SecureUtil.md5("123456"));
            // 保存到数据库
            this.adminMapper.insert(admin);
            // 添加角色
            Wrapper<Admin> queryWrapper2 = new QueryWrapper<>();
            ((QueryWrapper<Admin>) queryWrapper2).eq("username",username);
            Admin admin2 = this.adminMapper.selectOne(queryWrapper2);
            // 必选角色暂定为admin
            this.adminMapper.insertAdminAndRoleIdPressionId(admin2.getId(),1);
            String[] split = StrUtil.split(roleIds, ",");

            for (String s : split) {
                if(1 == Integer.valueOf(s)){ // 不重复添加
                    continue;
                }
                this.adminMapper.insertAdminAndRoleIdPressionId(admin2.getId(),Integer.valueOf(s));
            }

            return "新增管理员用户成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "新增管理员用户失败";
    }

    //修改管理员用户信息
    public String updateAdminById(Admin admin) {
        Long id = admin.getId();
        Wrapper<Admin> queryWrapper = new QueryWrapper<>();
        ((QueryWrapper<Admin>) queryWrapper).eq("id",id);
        Admin admin1 = this.adminMapper.selectOne(queryWrapper);
        if(admin1 == null ){
            return "你要修改的管理员用户id不存在";
        }

        // 用户名判断
        String username = admin.getUsername();
        Wrapper<Admin> queryWrapper1 = new QueryWrapper<>();
        ((QueryWrapper<Admin>) queryWrapper1).eq("username",username);
        ((QueryWrapper<Admin>) queryWrapper1).ne("id",id); // 这里有个坑，要不包含这个id的重名
        List<Admin> admins = this.adminMapper.selectList(queryWrapper1);
        if(admins.size() > 0){
            return "用户名已存在";
        }
        if(StrUtil.isEmpty(username)){
            return "用户名不能为空";
        }
        if(username.length()>4 || username.length()<2){
            return "用户名长度限制在2-4个字";
        }
        // 手机号判断
        String phone = admin.getPhone();
        if(StrUtil.isEmpty(phone)){
            return "非超级管理员手机号不能为空";
        }
        Wrapper<Admin> queryWrapper2 = new QueryWrapper<>();
        ((QueryWrapper<Admin>) queryWrapper2).eq("phone",phone);
        ((QueryWrapper<Admin>) queryWrapper2).ne("id",id);
        List<Admin> admins1 = this.adminMapper.selectList(queryWrapper2);
        if(admins1.size() > 0){
            return "手机号不能重复";
        }
        if(phone.length() != 11){
            return "手机号必须为中国11位手机号码";
        }

        this.adminMapper.updateById(admin);
        return "修改成功";
    }

    //删除管理员用户
    public String deleteAdminById(Integer adminId) {
        if(1 == adminId){
            return "超级管理员不能被删除";
        }
        Wrapper<Admin> queryWrapper = new QueryWrapper<>();
        ((QueryWrapper<Admin>) queryWrapper).eq("id",adminId);
        Admin admin = this.adminMapper.selectOne(queryWrapper);
        if(admin == null ){
            return "你要删除的管理员用户id不存在";
        }
        int i = this.adminMapper.deleteById(adminId);
        return "删除成功";
    }


    //修改密码
    public String updateAdminPasswordById(Integer id, String oldPassword, String newPassword, String newPasswordAgain) {
        Wrapper<Admin> queryWrapper = new QueryWrapper<>();
        ((QueryWrapper<Admin>) queryWrapper).eq("id",id);
        Admin admin = this.adminMapper.selectOne(queryWrapper);
        if(!admin.getPassword().equals(SecureUtil.md5(oldPassword))){
            return "旧密码输入错误";
        }

        if(!newPassword.equals(newPasswordAgain)){
            return "两次新密码输入不一致";
        }

        if(newPassword.length() < 6 || newPassword.length() >12){
            return "密码长度为6-12位";
        }
        admin.setPassword(SecureUtil.md5(newPassword));
        this.adminMapper.updateById(admin);
        return "修改密码成功";
    }
}
